package com.zkld.frame.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JWTUtil {

    //定义过期时间 7天
    private static final long OVER_DATE = 1000 * 60 * 60 * 24 * 7L;

    /**
     * 创建token
     *
     * @param userId
     * @param password
     * @return
     */
    public static String createToken(Integer userId, String password) {

        try {
            //定义所采用的加密算法
            Algorithm algorithm = Algorithm.HMAC256(password);
            return JWT.create().withClaim("userId", userId).withExpiresAt(new Date(System.currentTimeMillis() + OVER_DATE)).sign(algorithm);
        } catch (IllegalArgumentException | UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("创建Token异常", e);
        }

    }

    /**
     * 从token中获取指定键的值
     *
     * @param token
     * @return
     */
    public static Integer getUserId(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("userId").asInt();

    }

    /**
     * 定义验证token是否正确
     *
     * @param token
     * @param userId
     * @param password
     * @throws UnsupportedEncodingException
     */
    public static void isTrue(String token, Integer userId, String password) throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(password);
        JWTVerifier jwtVerifier = JWT.require(algorithm).withClaim("userId", userId).build();
        //校验token  若没有抛出异常则通过校验
        jwtVerifier.verify(token);
    }
}
